package com.adl.telawa.utils;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.adl.telawa.Initial;

/**
 * @author Adlane Achab.
 */
public class WatchDog extends Thread
{
	Object _obj;
	int _timeout;
	ConnectivityManager _cm;
	public static final WatchDog INSTANCE = new WatchDog();

	private WatchDog() {
		super("Telawa.Watchdog");
		start();
	}

	public void setConnectivityManager(ConnectivityManager cm)
	{
		_cm = cm;
	}

	public synchronized void set(Object obj, int timeout)
	{
		_obj = obj;
		_timeout = timeout;
	}

	public synchronized void remove()
	{
		_obj = null;
	}

	private void waitfor()
	{
		while (_obj == null)
		{
			try {Thread.sleep(2000);} catch (Throwable e) {}
		}
	}

	public void run()
	{
		NetworkInfo networkInfo;
		while (true)
		{
			try
			{
				waitfor();

				try {Thread.sleep(_timeout);} catch (Throwable e) {}

				while(_obj != null)
				{
					try {Thread.sleep(2000);} catch (Throwable e) {}
					networkInfo = _cm.getActiveNetworkInfo();
					if (networkInfo == null)
					{
						Initial.INSTANCE.info("Telawa: No connection available");
						try {Thread.sleep(5000);} catch (Throwable e) {}
						continue;
					}

					if (networkInfo.isAvailable() == false)
					{
						Initial.INSTANCE.info("Telawa: No connection available. Connection type: " + networkInfo.getTypeName() + "-" + networkInfo.getSubtypeName());
						try {Thread.sleep(5000);} catch (Throwable e) {}
						continue;
					}

					if (networkInfo.isConnected() == false)
					{
						Initial.INSTANCE.info("Telawa: No connected. Connection type: " + networkInfo.getTypeName() + "-" + networkInfo.getSubtypeName());
						try {Thread.sleep(5000);} catch (Throwable e) {}
						continue;
					}

					Initial.INSTANCE.info("Telawa: Slow connection. Connection type: " + networkInfo.getTypeName() + "-" + networkInfo.getSubtypeName());
					_obj = null;
				}
			}
			catch (Throwable e) {e.printStackTrace();}
		}
	}
}
